package org.ourgrid.worker.business.requester;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.interfaces.to.IncomingHandle;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.worker.business.controller.FileTransferController;
import org.ourgrid.worker.business.dao.WorkerDAOFactory;
import org.ourgrid.worker.business.dao.WorkerStatusDAO;
import org.ourgrid.worker.business.messages.WorkerControllerMessages;
import org.ourgrid.worker.request.IncomingTransferCompletedRequestTO;

public class IncomingTransferCompletedRequester implements RequesterIF<IncomingTransferCompletedRequestTO> {

	public List<IResponseTO> execute(IncomingTransferCompletedRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		IncomingHandle handle = request.getHandle();
		
		String senderPublicKey = request.getSenderPublicKey();

		WorkerStatusDAO workerStatusDAO = WorkerDAOFactory.getInstance().getWorkerStatusDAO();
		if (!workerStatusDAO.getConsumerPublicKey().equals(senderPublicKey)) {
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getUnknownClientSendsIncomingTransferCompletedMessage(senderPublicKey), LoggerResponseTO.WARN));
		    
			return responses;
		}
		
		if(WorkerDAOFactory.getInstance().getFileTransferDAO().getIncomingFile(handle) == null) {
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getIncomingTranferCompletedWithUnknownHandleMessage(handle.getId(), senderPublicKey), LoggerResponseTO.WARN));
			
			return responses;
		}

		if(workerStatusDAO.isFileTransferErrorState()) {
			responses.add(new LoggerResponseTO(WorkerControllerMessages.
					getWorkerWithErrorReceivesAnIncomingTransferCompletedMessage(handle.getId(), request.getAmountWritten(), senderPublicKey), LoggerResponseTO.WARN));
			
			return responses;
		}
		
		FileTransferController.getInstance().incomingTransferCompleted(handle, request.getAmountWritten(), responses);
		
		return responses;
	}
}
